package org.iabako.server.serviceimpl.user;

import org.iabako.server.conf.AppConf;
import org.iabako.server.dao.user.EnterpriseDAO;
import org.iabako.server.dao.user.UserDAO;
import org.iabako.server.mail.IabakoMailHelper;
import org.iabako.server.mail.IabakoMailSender;
import org.iabako.server.tools.BundleMessages;
import org.iabako.shared.entity.user.Enterprise;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.iservice.user.EmailVerificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * Created by jose on 06/01/15.
 */
@Service("emailVerificationService")
public class EmailVerificationServiceImpl implements EmailVerificationService {

    @Autowired
    IabakoMailSender iabakoMailSender;
    @Autowired
    UserDAO userDAO;
    @Autowired
    private AppConf appConf;
    @Autowired
    BundleMessages messages;
    @Autowired
    EnterpriseDAO enterpriseDAO;

    static private final Random random = new Random();

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public User sendKeyCode(String email, boolean userExistsVerification) {

        User user = userExistsVerification ? userDAO.getUserByEmail(email) : null;

        if (userExistsVerification && user == null) {
            return null;
        }

        if (!userExistsVerification) {
            //This is GoToDEMO Form
            //We persist temporal User to track prospects
            persistDemoUser(email);
        }

        HttpSession session = (((ServletRequestAttributes) RequestContextHolder.
                currentRequestAttributes()).getRequest()).getSession();

        Integer keyCode = random.nextInt((999999 - 100000) + 1) + 100000;

        session.setAttribute(email, keyCode);

        IabakoMailHelper iabakoMailHelper = new IabakoMailHelper(
                appConf.getNoReplyEmail(),
                appConf.getEmailPersonalFrom(), email,
                messages.getLabel("email_verification_subject", email),
                messages.getLabel("email_verification_body", keyCode + ""));

        iabakoMailSender.sendMail(iabakoMailHelper);

        return user;
    }

    private void persistDemoUser(String email) {
        Enterprise enterprise = enterpriseDAO.getDemoEnterprise();
        if (enterprise != null) {
            User userDemo = new User();
            userDemo.setFirstName("DEMO USER");
            userDemo.setLastName("DEMO USER");
            userDemo.setEmail(email);
            userDemo.setPassword("DEMO USER");
            userDemo.setEnterprise(enterprise);
            userDAO.persist(userDemo);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean verifyKeyCode(String email, String value) {

        HttpSession session = (((ServletRequestAttributes) RequestContextHolder.
                currentRequestAttributes()).getRequest()).getSession();

        Integer keyCode = (Integer) session.getAttribute(email);

        boolean emailConfirmed = (keyCode + "").equals(value);
        if (emailConfirmed) {
            session.removeAttribute(email);
            User user = userDAO.getDisableUserByEmail(email);
            if (user != null) {
                //If it's a password reminder, user can be null
                user.setEmailConfirmed(true);
                userDAO.merge(user);
            }
        }

        return emailConfirmed;
    }
}
